package com.rpc.core.server;

import com.rpc.core.RpcConfig;
import com.rpc.core.TaskExecutor;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 接收远程调用请求
 * @author wjwei
 */
public class ServerSocketInitial implements ApplicationListener<ContextRefreshedEvent> {

    private final RpcConfig rpcConfig;

    public ServerSocketInitial(RpcConfig rpcConfig) {
        this.rpcConfig = rpcConfig;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {

        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(rpcConfig.getPort());
            while (true) {
                Socket socket = serverSocket.accept();
                TaskExecutor.execute(new ServerSocketHandler(socket));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
